import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthService } from '../auth/auth.service';
import { IS_PUBLIC_KEY } from '../auth/public.decorator';

@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(
      private reflector: Reflector,
      private authService: AuthService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(
        IS_PUBLIC_KEY,
        [context.getHandler(), context.getClass()],
    );
    if (isPublic) return true;

    const request = context.switchToHttp().getRequest();
    const token = request.headers.authorization?.replace('Bearer ', '');
    if (!token) {
      throw new UnauthorizedException('请先登录'); // 自定义错误信息
    }

    try {
      request.user = await this.authService.validateToken(token);
    } catch (error) {
      // token 无效或验证失败
      throw new UnauthorizedException('登录失效');
    }
    return true;
  }
}